#include "../include/BST.h"
#include "../include/errorcodes.h"

//New
#define ERR_VFS_UPDATEFILE_03 "EXTERNAL_FILE_TOO_LARGE"


int update_file ( char *filePath,char *sourceFilePath )
{

	//printf("\n*************** IN Updatefile*******************\n");
	//MainHeader mhd;
	fd* data;
	FILE *fp;
	FILE *dataFile;
	int i=0,blockNo,file_offset=0;
	int fsize;
	char str[1024],ch;
	char sourcePath[50];
	
	strcpy(sourcePath,sourceFilePath);

	data=(fd *)malloc(sizeof(fd));
	
	data=bstSearchNode(&bstRoot,filePath);
	if(data==NULL)
	{
		printf("updatefile_FAILURE %s\n",ERR_VFS_UPDATEFILE_01);
		return;
	}
	
	//printf("blocknum in updatefile =%d",data->blockNum);
	//printf("\nsize in update=%d\n",data->fileSize);
	
	dataFile= fopen(sourcePath,"r");
	if(dataFile==NULL)
	{
		printf("updatefile_FAILURE %s\n",ERR_VFS_UPDATEFILE_02);
		return;
	}


	//printf("\n Contents of input file %s\n",str);

	if((data)!=NULL)
	{
		blockNo=data->blockNum;
		//printf("\n the block no is:%d",blockNo);
	}

	if((fp=fopen(header.fileSystemLabel,"rb+"))==NULL)
	{
		printf("updatefile_FAILURE %s\n",ERR_VFS_MOUNT_02);
	}
	else
	{
		fseek(fp,0,SEEK_SET);
		while(ch!='!')
		{
			fread(&ch,sizeof(ch),1,fp);
			file_offset++;
		}
		
		//printf("\noffset in update=%d\n",file_offset);
		//printf("\nblocknumber in update=%d\n",blockNo);
			
		fseek(fp,(file_offset+(blockNo*1024)),SEEK_SET);
		
		
		while((ch!= EOF))
		{
			ch=fgetc(dataFile);
			fwrite(&ch,sizeof(ch),1,fp);
			fsize++;
			//x++;
		}
		free(data);
		
	}
	fclose(fp);

printf("updatefile_SUCCESS\n");
	return 0;
}
